<template>
    <div style="padding: 0 17px">
        <Breadcrumb/>
        <div style="display: flex;flex-wrap: wrap; margin-top: 20px;">
            <div style="width: 350px;display: flex">
                <el-date-picker
                        v-model="searchData"
                        type="datetimerange"
                        range-separator="到"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                />
                <el-button type="primary"
                           style="color: #fff;font-size: 12px;background-color: #1890ff;margin-left: 15px"
                           @click="load">搜索
                </el-button>
            </div>

            <!-- 列筛选按钮 -->
            <el-button style="margin-left: 20px;" @click="showColumnSelector = true">
                列筛选
            </el-button>
        </div>

        <el-table
                :data="tableData"
                :row-style="{ height: '77px' }"
                border
                style="width: calc(100vw - 240px);margin-top: 20px;height: 70vh;color: #909399;font-size: 15px;"
                v-loading="loading">
            <!-- 固定列 -->
            <el-table-column prop="equipmentId" label="设备识别码" width="120" fixed="left"/>
            <el-table-column prop="sendTime" label="发送时间" width="160" fixed="left"/>
            <!-- 动态生成的列 -->
            <el-table-column
                    v-for="column in visibleColumns"
                    :key="column.prop"
                    :prop="column.prop"
                    :label="column.label"
                    :width="column.width"
                    show-overflow-tooltip>
                <template #default="scope">
                    <div v-if="column.prop === 'businesstype'">{{ getBusinessTypeMapText(scope.row.businesstype) }}
                    </div>
                    <div v-if="column.prop === 'messagetype'">{{ getEventTypeText(scope.row.messagetype) }}</div>
                    <div v-if="column.prop === 'devicetype'">{{ getDeviceTypeText(scope.row.devicetype) }}</div>
                    <div v-if="column.prop === 'batterys'">{{ getBatterysText(scope.row.batterys) }}</div>
                    <!--<div v-if="column.prop === 'tamperstatus'">{{ getTamperstatusText(scope.row.tamperstatus) }}</div>-->

                    <div v-if="column.prop === 'wpstatus'">{{ getWpstatusText(scope.row.wpstatus) }}
                    </div>
                    <div v-if="column.prop === 'wrstatus'">{{ getWstatusText(scope.row.wrstatus) }}</div>
                    <div v-if="column.prop === 'wdstatus'">{{ getWstatusText(scope.row.wdstatus) }}</div>
                    <div v-if="column.prop === 'wkstatus'">{{ getWstatusText(scope.row.wkstatus) }}</div>
                    <div v-if="column.prop === 'wostatus'">{{ getWstatusText(scope.row.wostatus) }}</div>
                    <div v-if="column.prop === 'collectiontime'">{{ formatCollectiontime(scope.row.collectiontime) }}</div>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
                :current-page="currentPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                :background="true"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />

        <!-- 列选择器对话框 -->
        <el-dialog title="选择要显示的列" v-model="showColumnSelector" width="600px">
            <div style="max-height: 400px; overflow-y: auto;">
                <el-checkbox-group v-model="selectedColumns">
                    <el-checkbox
                            v-for="column in allColumns"
                            :key="column.prop"
                            :label="column.prop"
                            style="display: block; margin: 10px 0;">
                        {{ column.label }}
                    </el-checkbox>
                </el-checkbox-group>
            </div>
            <template #footer>
                <el-button @click="showColumnSelector = false">取消</el-button>
                <el-button type="primary" @click="applyColumnSelection">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import request from "@/utils/request.js";
    import Breadcrumb from "@/components/Breadcrumb.vue";

    export default {
        name: "CurrentLsLog",
        components: {Breadcrumb},
        data() {
            return {
                currentData: {},
                searchData: [],
                tableData: [],  // 表单
                currentPage: 1,
                pageSize: 10,
                total: 0,
                loading: false,
                showColumnSelector: false,

                // 所有可能的列配置
                allColumns: [
                    {prop: "businesstype", label: "业务数据类型", width: 120},
                    {prop: "xdsmokelogid", label: "消息ID", width: 120},
                    {prop: "smokeid", label: "设备ID", width: 120},
                    {prop: "messagetype", label: "事件类型", width: 100},
                    {prop: "devicetype", label: "设备类型", width: 150},
                    {prop: "statedesc", label: "状态描述", width: 150},
                    {prop: "mac", label: "设备MAC", width: 150},
                    {prop: "ccid", label: "ICCID", width: 150},
                    {prop: "imsi", label: "IMSI", width: 150},
                    {prop: "dsignal", label: "信号强度", width: 100},
                    {prop: "batterys", label: "电池状态", width: 100},
                    {prop: "voltagevalue", label: "电池电压(mV)", width: 120},
                    {prop: "volvalue", label: "电量(%)", width: 120},
                    // {prop: "tvalue", label: "温度值(°C)", width: 120},
                    {prop: "dataunit", label: "数据单位", width: 100},
                    {prop: "data", label: "监测值", width: 120},
                    // {prop: "bjcode", label: "事件代码", width: 120},
                    // {prop: "imei", label: "IMEI", width: 150},
                    // {prop: "ccc", label: "防区号", width: 100},
                    // {prop: "tamperstatus", label: "防拆状态", width: 100},
                    // {prop: "cstatus", label: "保留字段", width: 100},

                    {prop: "monitorname", label: "监控数据", width: 120},
                    {prop: "dataunit", label: "数据单位", width: 100},
                    {prop: "wpstatus", label: "水压状态", width: 100},
                    {prop: "wrstatus", label: "变化率状态", width: 100},
                    {prop: "wdstatus", label: "倾斜状态", width: 100},
                    {prop: "wkstatus", label: "震动报警", width: 100},
                    {prop: "wostatus", label: "漏水状态", width: 100},
                    {prop: "singleflow", label: "本次流量", width: 120},
                    {prop: "totalflow", label: "累计流量", width: 120},
                    {prop: "collectiontime", label: "采集时间", width: 160},

                    {prop: "dtypename", label: "设备型号", width: 120},
                    {prop: "siaddress", label: "站点地址", width: 150},
                    {prop: "sitelname", label: "楼层", width: 120},
                    {prop: "installaddress", label: "详细地址", width: 150},
                    {prop: "longitude", label: "经度", width: 120},
                    {prop: "latitude", label: "纬度", width: 120}
                ],

                // 当前选中的列
                selectedColumns: [],

                // 当前显示的列
                visibleColumns: [],

                businessTypeMap: {
                    1: {text: "设备上报数据"},
                    3: {text: "设备在线离线事件"},
                    4: {text: "设备绑定事件（新增，修改）"},
                },
                eventTypeMap: {
                    0: {text: "其他"},
                    1: {text: "心跳"},
                    2: {text: "报警"},
                    3: {text: "报警恢复"},
                    4: {text: "防拆报警"},
                    5: {text: "防拆恢复",},
                    6: {text: "电池低压"},
                    7: {text: "电池低压恢复"},
                    8: {text: "自检"},
                    9: {text: "故障"},
                    10: {text: "故障恢复"},
                    11: {text: "测试",},
                    12: {text: "电量统计"},
                    13: {text: "温度报警"},
                    14: {text: "温度报警恢复"},
                    15: {text: "红外检测报警",},
                    16: {text: "红外检测报警恢复"},
                    17: {text: "气体浓度超标报警"},
                    18: {text: "气体浓度超标报警恢复"},
                },
                deviceTypeMap: {
                    "YG": {text: "烟雾探测器"},
                    "QG": {text: "气感探测器"},
                    "CO": {text: "一氧化碳探测器"},
                    "XS": {text: "一键报警按钮"},
                    "DQ": {text: "安全用电探测器"},
                    "JH": {text: "声光报警器"},
                    "HW": {text: "红外报警器"},
                    "SY": {text: "水压探测器"},
                },
                batterysMap: {
                    0: {text: "低压"},
                    1: {text: "正常"},
                },
                tamperstatusMap: {
                    0: {text: "闭合"},
                    1: {text: "打开"},
                },
            }
        },
        mounted() {
            // 初始化默认显示的列
            this.selectedColumns = this.allColumns.map(col => col.prop);
            this.visibleColumns = [...this.allColumns];
            this.load();
        },
        methods: {
            // 搜索及初始化
            load() {
                this.loading = true;
                let startTime = "", endTime = ""
                if (this.searchData !== null && this.searchData.length !== 0) {
                    startTime = this.searchData[0]
                    endTime = this.searchData[1]
                }
                request.get("/history-ls/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&equipmentInputStoreId=" + this.$route.query.equipmentInputStoreId + "&startTime=" + startTime + "&endTime=" + endTime).then(res => {
                    if (res.code === '200') {
                        for (let key in res.data) {
                            if (key === "record") {
                                this.tableData = res.data[key];
                            } else if (key === "total") {
                                this.total = res.data[key];
                            }
                        }
                    } else {
                        this.$message.error("错误" + res.msg)
                    }
                    this.loading = false;
                }).catch(() => {
                    this.loading = false;
                });
            },

            // 应用列选择
            applyColumnSelection() {
                this.visibleColumns = this.allColumns.filter(col =>
                    this.selectedColumns.includes(col.prop)
                );
                this.showColumnSelector = false;
            },

            reset(val) {
                this.isEdit = false;
                this.operationItemDialog = false;
                this.form = {};
                this.$refs[val].clearValidate();
            },

            // 删除确定弹窗
            deleteItem(scope) {
                this.$confirm('是否确定删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.get("/history-ls/delete/" + scope.id).then(res => {
                        if (res.code === '200') {
                            this.$message.success("成功")
                            this.load()
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                });
            },

            handleSizeChange(pageSize) {   // 改变当前每页的个数触发
                this.pageSize = pageSize
                this.load()
            },

            handleCurrentChange(pageNum) {  // 改变当前页码触发
                this.currentPage = pageNum
                this.load()
            },

            getBusinessTypeMapText(type) {
                return this.businessTypeMap[type]?.text || ``;
            },
            getEventTypeText(type) {
                return this.eventTypeMap[type]?.text || ``;
            },
            getDeviceTypeText(type) {
                return this.deviceTypeMap[type]?.text || ``;
            },
            getBatterysText(type) {
                return this.batterysMap[type]?.text || ``;
            },
            getTamperstatusText(type) {
                return this.tamperstatusMap[type]?.text || ``;
            },
            getWpstatusText(value) {
                if (value === 0) {
                    return "正常";
                } else if (value === 1) {
                    return "欠压";
                } else if (value === 2) {
                    return "过压";
                } else {
                    return "";
                }
            },

            getWstatusText(value) {
                if (value === 0) {
                    return "正常";
                } else if (value === 1) {
                    return "报警";
                } else {
                    return "";
                }
            },

            formatCollectiontime(value) {
                if (!value) return '';
                return new Date(value).toLocaleString();
            },
        }
    }
</script>

<style scoped>
    .el-checkbox {
        display: block;
        margin: 10px 0;
    }
</style>
